﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models.V1;

namespace DeviceCommons.DeviceMessages.Serialization.V2.Parsers
{
    public class DeviceMessageInfoReadingsParser : AbstractMessageParser<IDeviceMessageInfoReadings>, IDeviceMessageInfoReadingsParser, IContextAwareParser
    {
        private ParsingContext? _context;

        public DeviceMessageInfoReadingsParser() : base(new DeviceMessageInfoReadings())
        {
        }

        public override IDeviceMessageInfoReadings Parser(ReadOnlySpan<byte> bytes)
        {
            byte count = bytes[0];
            IDeviceMessageInfoReadings model = new DeviceMessageInfoReadings();
            model.ReadingArray = new IDeviceMessageInfoReading[count];
            var bytesTemp = bytes[1..];
            for (int i = 0; i < count; i++)
            {
                // 将上下文传递给子解析器
                if (DeviceMessageSerializerProvider.InfoReadingV2Par is IContextAwareParser contextAwareParser)
                {
                    contextAwareParser.SetContext(_context?.CreateChild());
                }
                
                model.ReadingArray[i] = DeviceMessageSerializerProvider.InfoReadingV2Par.Parser(bytesTemp);
                bytesTemp = bytesTemp[model.ReadingArray[i].DataLength..];
            }
            Model = model;
            return model;
        }

        public void SetContext(ParsingContext context)
        {
            _context = context;
        }

        public ParsingContext? GetContext()
        {
            return _context;
        }
    }
}
